package com.hengda.smart.speak.d.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.support.annotation.Nullable;


import com.hengda.smart.speak.d.bean.RecorderFile;
import com.hengda.smart.speak.d.config.RecorderConstant;
import com.hengda.smart.speak.d.config.Utility;
import com.hengda.smart.speak.d.media.MediaConstant;

import java.io.File;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author WZQ
 * @version V1.0
 * @Description ${音频服务}
 * @Email :wzq_steady@126.com
 * @date 2016/7/22 13:03
 * @update (date)
 */
public class RecorderService extends Service {

    int myBufferSize = 8192;
    private boolean isSaved = false;
    private boolean isPaused = false;
    private boolean hasRecorded = false;
    private SharedPreferences preferences;
    int channel = 1, rate = 8000, format = MediaRecorder.OutputFormat.THREE_GPP;

    private MediaRecorder mRecorder;
    private String outputFile = "";
    private volatile boolean isRecording = false;
    private volatile boolean isPlaying = false;
    String path = "";
    private MediaPlayer mPlayer;
    private AudioRecord mAudioRecord;
    private String extension = "amr";
    //Intent传递内容
    private String taskID = "";
    private int  msg = 0;
    public static final String TAG_TASKID = "TAG_TASKID";
    public static final String TAG_MSG    = "TAG_MSG";
    //周期性任务
    private Timer timer;
    private TimerTask timerTask;
    private String loacalTaskId ="hengda";

    private Intent musicIntent;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        path= Utility.ROOT_FOLDER;
        musicIntent= new Intent(this, MusicService.class);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            taskID = intent.getStringExtra(TAG_TASKID);
            msg = intent.getIntExtra(TAG_MSG, 0);                  //操作信息
            if (msg == RecorderConstant.MSG.START_RECORDING) {     //开启录音线程
                if(!loacalTaskId.equals(taskID)){
                    musicIntent.putExtra("MSG", MediaConstant.MSG.MIC_PAUSE);
                    startService(musicIntent);
                    timeTaskExe(taskID);
                }
            } else if (msg == RecorderConstant.MSG.STOP_RECORDER) {//暂停
                taskID="admin";
                timer.cancel();
                stopRecording();
            }
        } catch (Exception e) {

        }
        return super.onStartCommand(intent, flags, startId);
    }



    /**
     * 开始进行文件录制
     * @param taskID
     */
    public void startRecorder(String taskID){
//        Logger.d("开始进行录制"+taskID);
        prepareRecorder(taskID);
        try {
            mRecorder.prepare();
            mRecorder.start();
            isRecording = true;
            hasRecorded = true;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  执行周期性任务
     */
    public void timeTaskExe(final String ID){
        loacalTaskId=ID;
        mRecorder=null;
        timer=new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
//                Logger.d("执行timer任务");
                if(mRecorder!=null){
                    stopRecording();
                }
                startRecorder(ID);
            }
        };
        timer.schedule(timerTask, 0, 3*60*1000+1000);
    }

    private void prepareRecorder(String taskID) {
        format= MediaRecorder.OutputFormat.AMR_NB;
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(format);
        mRecorder.setAudioChannels(channel);
        mRecorder.setAudioSamplingRate(rate);
        if (format == MediaRecorder.OutputFormat.THREE_GPP) {
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            extension = "3gp";
        }
        if (format == MediaRecorder.OutputFormat.MPEG_4) {
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            extension = "mp4";
        }
        if (format == MediaRecorder.OutputFormat.AMR_NB) {
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            extension = "amr";
        }
        String outputDir = path+"/"+taskID+"/";
        if(!new File(outputDir).exists()){
            new File(outputDir).mkdirs();
        }
        outputFile = path +"/"+taskID+"/"+taskID+(new Date().getTime()) + "." + extension;
        RecorderFile recorderFile = new RecorderFile();
        recorderFile.setFilePath(outputFile);
        recorderFile.setFileName(taskID+(new Date().getTime()));
        recorderFile.setFileTaskId(taskID);
        recorderFile.setFileUpLoadState(0);
//        recorderFile.save();
        mRecorder.setOutputFile(outputFile);
    }

    /**
     *  关闭录音服务
     */
    public void stopRecording(){
//        Logger.d("关闭录制"+taskID);
        if(mRecorder!=null){
            mRecorder.stop();
        }
        isRecording = false;
        mRecorder.reset();
    }

    @Override
    public void onDestroy() {
        if(mRecorder!=null){
            mRecorder.stop();
        }
        super.onDestroy();
    }
}
